package com.bs.jianli.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bs.jianli.entity.Menu;
import com.bs.jianli.entity.Role;
import com.bs.jianli.entity.User;
import com.bs.jianli.service.IMenuService;
import com.bs.jianli.service.IRoleService;
import com.bs.jianli.service.IUserService;
import com.bs.jianli.service.IUserroleService;
import com.bs.jianli.util.Result;
import com.bs.jianli.util.UUIDFactory;
import com.bs.jianli.util.auto.Auth;
import com.bs.jianli.util.exception.NoPwdException;
import com.bs.jianli.util.exception.NotUserException;
import com.bs.jianli.util.exception.ServiceException;
import com.bs.jianli.util.pwd.MD5SaltUtils;
import com.bs.jianli.util.redis.RedisUtils;
import com.bs.jianli.util.redis.TokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author yao
 * @since 2023-01-13
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理系统")
public class UserController {
    @Resource
    IUserService service;

    @Resource
   IUserroleService userroleService;

    @Resource
    IRoleService roleService;

    @Resource
    IMenuService menuService;

    @Resource
    RedisUtils utils;
    @Resource
     HttpServletRequest request;

    @Resource
    PasswordEncoder encoder;

    String salt="baisi";



    @ApiOperation("用户列表")
    @GetMapping
    @Auth("system:user")
    @PreAuthorize("@auth.getAuth('system:user')")
    public Result index(@RequestParam(defaultValue = "1") @ApiParam("当前页") Integer pageNum, @RequestParam(defaultValue = "5")  @ApiParam("页面大小") Integer pageSize, @RequestParam(defaultValue = "") @ApiParam("用户名") String name){
        Page<User> page=new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
        lq.like(StringUtils.isNotBlank(name),User::getUsername,name);
        page=service.page(page,lq);
        return Result.success(page);
    }


    @ApiOperation("添加用户")
    @PostMapping("/add")
    public Result add(@RequestBody @ApiParam("用户表")User menu){
        menu.setPassword(encoder.encode(menu.getPassword()));
        boolean save = service.save(menu);
        if(save){
            return Result.success("添加成功");
        }else{
            return Result.success("添加失败");

        }
    }

    @ApiOperation("根据用户id查询单个用户")
    @GetMapping("/{id}")
    public Result getByMenu(@PathVariable("id") @ApiParam("用户id") String id){
        User menu = service.getById(id);
        List<Role> roles = roleService.addRoles(menu.getUserid());
        menu.setRoles(roles);
        return Result.success(menu);
    }

    @ApiOperation("用户修改")
    @PutMapping
    public Result update(@RequestBody @ApiParam("用户表") User menu){
        User menu1 = service.getById(menu.getUserid());
        menu.setVersion(menu1.getVersion());
        boolean update = service.updateById(menu);
        if(update){
            return Result.success("修改成功");
        }else{
            return Result.success("修改失败");
        }
    }


    @ApiOperation("用户删除")
    @DeleteMapping("/{id}")
    public Result del(@PathVariable("id") @ApiParam("用户id") String id){
        boolean del = service.removeById(id);
        if(del){
            return Result.success("删除成功");
        }else{
            return Result.success("删除失败");

        }
    }

    @ApiOperation("给用户授角色")
    @GetMapping("/addUsers")
    public Result addUser(@ApiParam("用户id") @RequestParam String userid,@ApiParam("角色id") @RequestParam String[] roleids){
        int row = userroleService.addUser(userid, roleids);
        if(row>0){
            return Result.success("给用户授角色成功");
        }else{
            return Result.success("给用户授角色失败");
        }
    }

    /*@PostMapping("/login")
    public Result login(String username, String password){
       if(StringUtils.isBlank(username)){
           throw new NotUserException("用户名不能为空");
       }
       LambdaQueryWrapper<User> lq=new LambdaQueryWrapper<>();
       lq.eq(User::getUsername,username);
        User user = service.getOne(lq);
        if(user==null){
            throw new NotUserException("您还未登录");
        }
        if(StringUtils.isBlank(password)){
            throw new NoPwdException("密码不能为空");
        }
        if (MD5SaltUtils.equals(password,salt,user.getPassword())){
            if(user.getStatus()==1){
                throw new ServiceException("该用户已被冻结");
            }else if (user.getStatus()==2){
                throw new ServiceException("该用户已被注销");
            }
            String token = UUIDFactory.UUID();
            List<Role> roles = roleService.addRoles(user.getUserid());
            user.setRoles(roles);
            List<Menu> menus = menuService.byMenus(user.getUserid(), "0");
            user.setMenus(menus);
            List<String> strings = menuService.byPression(user.getUserid());
            Set<String> sets=new HashSet<>(strings);
            user.setPression(sets);
            HttpSession session = request.getSession();
            Map<String,Object> maps=new HashMap<>();
            maps.put("user",user);
            maps.put("token",token);
            //session.setAttribute("user",user);
            utils.set(token,user,TokenUtil.TOKEN_TIME);
            return Result.success(maps);
        }else{
            throw new NoPwdException("您的密码输入有误");
        }
    }*/

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        Map<String, Object> login = service.login(user);
        return Result.success(login);

    }


    @GetMapping("/edit")
    public Result edit(){
        service.edit();
        return Result.success("退出成功");
    }
}

